#include "key.h"
#include "main.h"

static KeyInfo info;

/**
 * @brief 获取按下按键
 * @details 获取按下按键的名称，如果没有按键被按下，则返回KEY_NO_NAME
 * @return
 */
KeyName key_get_pressed() {
    if (!HAL_GPIO_ReadPin(Encoder_KEY_GPIO_Port, Encoder_KEY_Pin)) return KEY_ENCODER;
    if (!HAL_GPIO_ReadPin(KEY1_GPIO_Port, KEY1_Pin)) return KEY_LEFT;
    if (!HAL_GPIO_ReadPin(KEY2_GPIO_Port, KEY2_Pin)) return KEY_MIDDLE;
    if (!HAL_GPIO_ReadPin(KEY3_GPIO_Port, KEY3_Pin)) return KEY_RIGHT;
    return KEY_NO_NAME;
}

/**
 * @brief 按键消抖
 * @return
 */
KeyName key_debounce() {
    static KeyName name;
    name = key_get_pressed();
    if (name != KEY_NO_NAME) {
        HAL_Delay(10);
        name = key_get_pressed();
        if (name != KEY_NO_NAME) {
            return name;
        }
    }
    return KEY_NO_NAME;
}

/**
 * @brief 按键扫描函数
 * @return
 */
KeyInfo key_scan() {
    static uint8_t key_level;
    static uint8_t key_hold;
    static uint32_t tick;
    static KeyName name;

    name = key_debounce(); // 按键消抖
    if (name != KEY_NO_NAME) {
        if (!key_level) { // 检测上升沿
            info.state = KEY_SINGLE_CLICKED;
            info.name = name;
            key_level = 1;
            if(HAL_GetTick() - tick < KEY_DOUBLE_CLICKED_THRESHOLD_MS) // 检测双击
            {
                info.state = KEY_DOUBLE_CLICKED;
            }
            tick = HAL_GetTick();
        }else if(!key_hold && HAL_GetTick() - tick > KEY_LONG_PRESS_THRESHOLD_MS){ // 检测长按
            info.state = KEY_LONG_PRESSED;
            key_hold = 1;
        }
    } else if (name == KEY_NO_NAME) { // 按键释放
        key_level = 0;
        key_hold = 0;
    }
    return info;
}

/**
 * @brief 清除标志位
 */
void key_clear_flags()
{
    info.state = KEY_CLEAR;
}
